#include "slope1c1.h"
     #define true 1
     #define false 0
     typedef unsigned char bool;

DIF_tstSlopeDpoolData DIF_stSlopeDpoolData = {0,0,1};



/*slope init function */
void slope_vInit(void)
{

}
/*slope main function */
void slope_vMain(void)
{
    // 1. 读取输入信号
    uint8 canPitchSign = SYN__u8PitchAngleSign(); // 0:上坡 1:下坡
    uint8 canPitchAng = SYN__u8PitchAng();        // 0x00~0x5A有效
    bool pitchSignTimeout = Flg_PitchAngSign_tmout();
    bool pitchAngTimeout = Flg_PitchAng_tmout;
    bool pitchSignFirst = Flg_PitchAngSign_fv();
    bool pitchAngFirst = Flg_PitchAng_fv();

    static uint8 lastValidDirection = 0; // 0:水平 1:上坡 2:下坡
    static uint8 lastValidAngle = 0;
    static uint8 lastValidUnit = 1; // 1:度
    static uint8 lostSignalCnt = 0;
    const uint8 TIMEOUT_CYCLE = 10;

    // 2. 信号超时计数
    if (pitchSignTimeout || pitchAngTimeout) {
        if (lostSignalCnt < TIMEOUT_CYCLE) lostSignalCnt++;
    } else {
        lostSignalCnt = 0;
    }

    // 3. 判断是否用最后一次有效值
    bool useLastValue = false;
    if (lostSignalCnt >= TIMEOUT_CYCLE) {
        useLastValue = true;
    }

    // 4. 真值表映射
    if (!useLastValue && canPitchAng <= 0x5A) {
        if (canPitchAng == 0x00) {
            // 水平
            DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = 0;
            DIF_stSlopeDpoolData.DIF_u8SlopeAngleValue = 0;
            DIF_stSlopeDpoolData.DIF_u8SlopeUnit = 1;
            lastValidDirection = 0;
            lastValidAngle = 0;
            lastValidUnit = 1;
        } else {
            // 有效坡度
            if (canPitchSign == 0) {
                // 上坡
                DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = 1;
            } else {
                // 下坡
                DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = 2;
            }
            DIF_stSlopeDpoolData.DIF_u8SlopeAngleValue = canPitchAng;
            DIF_stSlopeDpoolData.DIF_u8SlopeUnit = 1;
            lastValidDirection = DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue;
            lastValidAngle = canPitchAng;
            lastValidUnit = 1;
        }
    } else if (!useLastValue && canPitchAng >= 0x5B && canPitchAng <= 0x7F) {
        // 保留值，显示上次有效值
        DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = lastValidDirection;
        DIF_stSlopeDpoolData.DIF_u8SlopeAngleValue = lastValidAngle;
        DIF_stSlopeDpoolData.DIF_u8SlopeUnit = lastValidUnit;
    } else if (useLastValue) {
        // 超时，显示上次有效值
        DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = lastValidDirection;
        DIF_stSlopeDpoolData.DIF_u8SlopeAngleValue = lastValidAngle;
        DIF_stSlopeDpoolData.DIF_u8SlopeUnit = lastValidUnit;
    } else {
        // 未收到有效信号且未超时，显示初始值0
        DIF_stSlopeDpoolData.DIF_u8SlopeDirectionValue = 0;
        DIF_stSlopeDpoolData.DIF_u8SlopeAngleValue = 0;
        DIF_stSlopeDpoolData.DIF_u8SlopeUnit = 1;
    }
}
